<?php
/**
 * @author all@cosmos-framework.org
 * @copyright (c) 2013 cosmos-framework.org
 * @license http://www.opensource.org/licenses/mit-license.php
 * @link http://cosmos-framework.org/
 * @package cosmos.framework
 * @version 2.0
 */
namespace Cosmos;

class Memcache extends \Memcache {

    /**
     * @global $_MEMCACHES[][ host, port, persistent ]
     */
    public static function & connects() {

        static $_connects;
        if (!$_connects) {

            global $_MEMCACHES;

            $_connects = new self();
            $_connects->addServers($_MEMCACHES);
        }

        return $_connects;
    }

    /**
     * @param string[][ host, port, persistent ]
     */
    public function addServers($envs) {

        foreach ((array) $envs as $env) {

            // response pool.
            call_user_func_array(array($this, 'addServer'), $env);
        }
    }

    /**
     * @param string $k
     * @param int $expire
     * @return mixed
     */
    public function fetch($k, $expire = 0) {

        if ($this->get(PHP_EOL . $k)) {

            // in response.
            return $this->get($k);
        }

        // response null.
        $this->set(PHP_EOL . $k, 1, 0, $expire);
    }

    /**
     * @param string $domain
     * @param int $expire
     * @return string
     */
    public function group($domain, $expire = 0) {

        if (!$response = $this->get($domain)) {

            // mapped fill.
            $this->set($domain, $response = uniqid('', true), 0, $expire);
        }

        // response id.
        return $response;
    }

    /**
     * @param string $k
     * @param string $response
     * @param int $flag
     * @param int $expire
     * @return boolean
     */
    public function set($k, $response, $flag = 0, $expire = 0) {

        Logger::debug(__METHOD__ . sprintf('(%s,%s,%s,%s)', $k, json_encode($response), $flag, $expire));

        return parent::set($k, $response, $flag, $expire);
    }

}
